package com.jy.api.controller.pos;


import com.jy.api.dao.*;
import com.jy.api.domain.*;
import com.jy.api.service.OrderService;
import com.jy.api.service.SequenceService;
import com.jy.api.signUpReq.pos.MemberSignUpReq;
import com.jy.api.util.Contens;
import com.jy.api.util.MyDateUtils;
import com.jy.api.util.ParseErrors;
import com.jy.api.util.UuidUtil;
import com.jy.api.vo.pos.member.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.security.Principal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping(value = "v1/pos", produces = "application/json;charset=utf-8")
public class PosMemberController {


    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @Autowired
    MemberDao memberDao;



    @Autowired
    ChargeRuleDao chargeRuleDao;

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderService orderService;
    @Autowired
    MemberAccountDao memberAccountDao;
    @Autowired
    private MemberTeamAccountDao teamAccountDao;
    @Autowired
    private TeamTransactionDao teamTransactionDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    SequenceService sequenceService;

    /**
     * 会员查询
     * 目前只支持会员号，名字。
     * 只支持左，模糊查询
     *
     * @param storeId
     * @param q
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/members")
    public ResponseEntity queryMember(@RequestParam(name = "storeId") String storeId,
                                      @RequestParam(name = "q", defaultValue = "") String q) {
        try {
            List<MemberVo> memberVos = new ArrayList<>();
            List<Object[]> objects = memberDao.getMember(storeId, q);
            for (Object[] o : objects) {
                MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                        o[2] != null ? o[2].toString() : "", o[3].toString(),
                        Double.parseDouble(o[4].toString()),
                        o[5].toString(),o[8].toString());
                memberVos.add(memberVo);
            }
            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(storeId, true);
            if (teamTransaction != null) {
                objects = memberDao.getMemberTeam(teamTransaction.getTeamId(), q);
                for (Object[] o : objects) {
                    MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                            o[2] != null ? o[2].toString() : "", o[3].toString(),
                            Double.parseDouble(o[4].toString()),
                            o[5].toString(),o[6].toString());
                    memberVos.add(memberVo);
                }
            }
            return new ResponseEntity(memberVos, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMember is error==> storeId:{},q:{}", storeId, q, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 添加店铺会员信息
     *
     * @param storeId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/add/members")
    public ResponseEntity addMembers(@RequestParam(name = "storeId") String storeId, @RequestParam("mobile") String mobile, @RequestParam("name") String name) throws Exception {
        Member member = memberDao.findTop1ByMobileOrderByUpdateTimeDesc(mobile);
        if (member == null) {
            member = new Member(UuidUtil.getUuid(), name,
                    UuidUtil.getUuid());
            member.setMobile(mobile);
            member.setCode(MyDateUtils.dateToString8(new Date()) + String.format("%06d",
                    sequenceService.generate("memberCode")));
            MemberAccount memberAccount = new MemberAccount();
            memberAccount.setStoreId(storeId);
            memberAccount.setId(UuidUtil.getUuid());
            member.getAccounts().add(memberAccount);
            memberAccountDao.save(memberAccount);
            memberDao.save(member);
        } else {
            boolean check = false;
            for (MemberAccount account : member.getAccounts()) {
                if (account.getStoreId().equals(storeId)) {
                    check = true;
                }
            }
            if (!check) {
                MemberAccount account = new MemberAccount();
                account.setStoreId(storeId);
                account.setId(UuidUtil.getUuid());
                member.getAccounts().add(account);
                memberAccountDao.save(account);
                memberDao.save(member);
            } else {
                return new ResponseEntity("该手机号已是本店会员，请勿重复添加", HttpStatus.BAD_REQUEST);
            }
        }
        return ResponseEntity.ok("添加成功");
    }

    /**
     * 会员充值
     *
     * @param id
     * @param memberSignUpReq
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, value = "/member-charges/{id}")
    public ResponseEntity addMemberCharges(@PathVariable String id,
                                           @RequestBody MemberSignUpReq memberSignUpReq,
                                           Principal principal) {
        try {
            Set<ConstraintViolation<MemberSignUpReq>> memberErrors =
                    validator.validate(memberSignUpReq);
            if (!memberErrors.isEmpty()) {
                return new ResponseEntity(ParseErrors.getErrors(memberErrors), HttpStatus.BAD_REQUEST);
            }

            Order order = orderDao.findOne(id);
            if (order != null) {
                return new ResponseEntity("订单id已存在", HttpStatus.BAD_REQUEST);
            }
            ChargeRule chargeRule = null;
            if (StringUtils.isNotBlank(memberSignUpReq.getChargeRuleId())) {
                chargeRule = chargeRuleDao.findOne(memberSignUpReq.getChargeRuleId());
                if (chargeRule == null || !chargeRule.isEnabled()) {
                    return new ResponseEntity("充送规则不存在", HttpStatus.BAD_REQUEST);
                }
            }
            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(memberSignUpReq.getStoreId(), true);
            MemberTeamAccount teamAccount = null;
            if (teamTransaction != null) {
                teamAccount = teamAccountDao.findByMemberIdAndEnabledAndTeamId(memberSignUpReq.getMemberId(), true, teamTransaction.getTeamId());
            }
            MemberAccount memberAccount = memberAccountDao.getStoreIdAndMemberId(memberSignUpReq.getStoreId(),
                    memberSignUpReq.getMemberId());
            if (teamAccount == null && memberAccount == null) {
                return new ResponseEntity("该会员无对应店铺帐户", HttpStatus.BAD_REQUEST);
            }
            Order orderNew = orderService.addMemberOrder(id, memberSignUpReq.getAmount(), memberSignUpReq.getUserName(),
                    memberSignUpReq.getStoreId(), memberSignUpReq.getMemberId(), chargeRule, memberSignUpReq.getType());
            return new ResponseEntity(orderNew, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("addMemberCharges is error==> id:{},memberSignUpReq:{}", id, memberSignUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 会员信息获取
     *
     * @param storeId
     * @param memberId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{storeId}/members")
    public ResponseEntity getMemberInfo(@PathVariable String storeId,
                                        @RequestParam(value = "memberId", required = false) String memberId) {
        try {
            List<MemberVo> memberVos = new ArrayList<>();
            List<Object[]> objects = memberDao.getMemberById(storeId, memberId);
            Map<String,Object> map = new HashMap<>();
            for (Object[] o : objects) {
                MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                        o[2] != null ? o[2].toString() : "", o[3].toString(),
                        Double.parseDouble(o[4].toString()),
                        o[5].toString(),o[6].toString());
                memberVos.add(memberVo);
            }
            TeamTransaction teamTransaction = teamTransactionDao.findByStoreIdAndEnable(storeId, true);
            if (teamTransaction != null) {
                objects = memberDao.getMemberTeamById(teamTransaction.getTeamId(), memberId);
                for (Object[] o : objects) {
                    MemberVo memberVo = new MemberVo(o[0].toString(), o[1].toString(),
                            o[2] != null ? o[2].toString() : "", o[3].toString(),
                            Double.parseDouble(o[4].toString()),
                            o[5].toString(),o[6].toString());
                    memberVos.add(memberVo);
                }
            }
            map.put("amount",memberVos.get(0).getAmount());
            map.put("code",memberVos.get(0).getCode());
            map.put("id",memberVos.get(0).getId());
            map.put("mobile",memberVos.get(0).getMobile());
            map.put("name",memberVos.get(0).getName());
            map.put("points",memberVos.get(0).getPoints());
            return new ResponseEntity(map, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("queryMember is error==> storeId:{},q:{}", storeId, memberId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 会员信息获取
     *
     * @param storeId
     * @param code
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/{storeId}/members-code")
    public ResponseEntity getMemberCodeInfo(@PathVariable String storeId,
                                            @RequestParam(name = "code") String code) {
        try {
            List<Map<String, Object>> member = memberDao.getCodeMemberInfo(storeId,
                    code);
            if (member.size() == 0) {
                return new ResponseEntity("查询失败！会员信息不存在！", HttpStatus.BAD_REQUEST);
            }
            return new ResponseEntity(member.get(0), HttpStatus.OK);
        } catch (Exception ex) {
            log.error("getMemberInfo is error==> storeId:{},code:{}", storeId, code, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
